package com.gdkj.tencent;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gdkj.common.LogicResult;
import com.gdkj.constant.CommonConstant;
import com.gdkj.constant.RedisConstant;
import com.gdkj.util.HttpUtils;
import com.gdkj.util.TLSSigAPIv2;
import com.google.common.collect.Maps;
import com.xjgks.common.constant.HttpResultConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Component
@Slf4j
public class ImApi {

    @Value("${TCIM_SDK_APPID}")
    private String imAppId;

    @Value("${TCIM_SDK_KEY}")
    private String imKey;

    @Value("${TCIM_IDENTIFIER}")
    private String imAdmin;

    private String baseUri = "https://console.tim.qq.com";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取签名
     * @param uid
     * @return java.lang.String
     */
    public String getSignByUid(String uid) {
        String signRedisKey = RedisConstant.IM_SIGN_PREFIX + uid;
        String signStr = stringRedisTemplate.opsForValue().get(signRedisKey);
        if (StrUtil.isNotEmpty(signStr)) {
            return signStr;
        }

        GenerateTestUserSig.SDKAPPID = Integer.parseInt(imAppId);
        GenerateTestUserSig.SECRETKEY = imKey;
        GenerateTestUserSig.EXPIRETIME = RedisConstant.IM_SIGN_CASH_TIME;
        log.info("获取签名参数为:" + GenerateTestUserSig.SDKAPPID + "," + GenerateTestUserSig.SECRETKEY);
        signStr = GenerateTestUserSig.genTestUserSig(uid);
        stringRedisTemplate.opsForValue().set(signRedisKey, signStr, Duration.ofSeconds(RedisConstant.IM_SIGN_CASH_TIME));
        return signStr;
    }

    public LogicResult send(Object body, String serviceName, String command) throws Exception {
        String requestUrl = getRequestUrl(serviceName, command);
        Map<String, String> headers = Maps.newHashMap();
        headers.put("Content-Type", "application/json");
        String responseStr = HttpUtils.doPostJson(requestUrl, JSONObject.toJSONString(body), headers, CommonConstant.HTTP_TIME_OUT);
        ImResponse imResponse = JSONObject.parseObject(responseStr, ImResponse.class);
        if (imResponse == null) {
            return LogicResult.build(HttpResultConstants.EXCEPTION_CODE, null, "腾讯返回数据异常");
        }
        if (CommonConstant.SIGN_EXPIRE.equals(imResponse.getErrorCode())) {
            String signRedisKey = RedisConstant.IM_SIGN_PREFIX + imAdmin;
            stringRedisTemplate.delete(signRedisKey);
        }
        if (CommonConstant.IM_OK_STATE.equals(imResponse.getActionStatus())) {
            return LogicResult.build(HttpResultConstants.SUCCESS_CODE, imResponse, "成功");
        }
        return LogicResult.build(HttpResultConstants.EXCEPTION_CODE, imResponse.getErrorCode(), imResponse.getErrorInfo());
    }

    public String getRequestUrl(String serviceName, String command) {
        Random random = new Random();
        Integer randomNumber = random.nextInt();
        return String.format("%s/v4/%s/%s?sdkappid=%s&identifier=%s&usersig=%s&random=%d&contenttype=json", baseUri, serviceName, command, imAppId, imAdmin, getSignByUid(imAdmin), randomNumber);
    }

    public JSONObject toPost(String apiUrl, Map<String, Object> postMap) throws UnsupportedEncodingException {
        TLSSigAPIv2 api = new TLSSigAPIv2(Long.valueOf(imAppId), imKey);
        //生成用户签名
        String userSig = api.genUserSig(imAdmin, 180 * 86400);
        String random = IdUtil.randomUUID();
        String post = JSON.toJSONString(postMap);
        //拼接实际URL
        String url = baseUri + apiUrl + "?usersig=" + userSig + "&identifier=" + imAdmin + "&sdkappid=" + String.valueOf(imAppId) + "+&random=" + random + "&contenttype=json";
        //请求消息头
        Map<String, Object> headMap = new HashMap<String, Object>();
        headMap.put("Content-Type", "text/plain;charset=UTF-8");

        String httpClientResult = HttpUtils.httpPostRequest(url, headMap, post);
        JSONObject groupInfo = JSONObject.parseObject(httpClientResult);
        log.info("im添加用户返回消息：{}"+JSONObject.toJSONString(groupInfo));
        return groupInfo;
    }
    
    
}
